import {Component, OnInit} from '@angular/core';
import {Service} from '../service/service';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-manager',
  templateUrl: './manager.component.html',
  styleUrls: ['./manager.component.scss']
})
export class ManagerComponent implements OnInit {
  public list: Array<object> = [];
  public role: Array<object> = [];
  public edit: object = {};
  public visible = false;
  public isSuper: Array<object> =  [
    { name: '是', val: 1 },
    { name: '否', val: 0 }
    ];

  constructor(private service: Service, public msg: NzMessageService) {
    this.getManager();
    this.getAllRole();
  }

  ngOnInit(): void {

  }

  async getManager() {
    const result: object = await this.service.getManager(null);
    this.list = result.data.data;
    console.log(this.list);
  }

  async getAllRole() {
    const result: object = await this.service.getAllRole(null);
    this.role = result.data.data;
    console.log(this.role);
  }

  showModal(data) {
    if (data) {
      this.edit = data;
      this.edit.password = '';
    } else {
      this.edit = {
        username: '', password: '', email: '', phone: '', role_id: '', is_super: 0
      };
    }
    console.log(this.edit);
    this.visible = true;
  }

  async update() {
    console.log(this.edit);
    if (this.edit._id) {
      const {_id, username, password, email, mobile, role_id, is_super} = this.edit;
      const data = {
        _id, username, password, email, mobile, role_id, is_super
      };
      const result: object = await this.service.editManager(data);
      console.log(result);
      if (result.data.code === 200) {
        this.msg.info('修改用户信息成功');
        this.getManager();
      }
    } else {
      const {username, password, email, mobile, role_id, is_super} = this.edit;
      const data = {
        username, password, email, mobile, role_id, is_super
      };
      const result: object = await this.service.addManager(data);
      console.log(result);
      if (result.data.code === 200) {
        this.msg.info('添加用户信息成功');
        this.getManager();
      }
    }
    this.close();
  }

  close(): void {
    this.edit = {};
    this.visible = false;
  }

  cancel(): void {

  }

  async confirm(_id): void {
    const data = {_id};
    const result: object = await this.service.deleteManager(data);
    console.log(result);
    if (result.data.code === 200) {
      this.msg.info('删除用户信息成功');
      this.getManager();
    }
  }
}
